# coding=utf-8

from . import admin
from flask import request, render_template, jsonify
from app import PAGE_NUM, page_code, util
from dbConnection.MysqlConn import Mysql
import math, time
import sys

reload(sys)
sys.setdefaultencoding('utf8')


# 商家列表
@admin.route('/admin/business_list.html')
@util.admin_login
def business_list():
    return render_template('admin/business/business_list.html')


# 获取商家列表数据
@admin.route('/admin/business_list_post', methods=['post'])
@util.admin_login
def business_list_post():
    parms = ['uid', 'day']
    maps = {}
    for d in parms:
        maps[d] = request.values.get(d)
    p = request.values.get('p', 1)
    c_num = (int(p) - 1) * PAGE_NUM
    sql = "select * FROM user_business WHERE 1=1"
    sql2 = "select count(*) con,sum(money) as total_money,sum(wash_num) as total_num FROM user_business WHERE 1=1"
    if maps['uid']:
        sql += " and (bid = '%s' " % maps['uid']
        sql += " or nickname like '%" + maps['uid'] + "%')"
        sql2 += " and (bid = '%s' " % maps['uid']
        sql2 += " or nickname like '%" + maps['uid'] + "%')"
    if maps['day']:
        s_str = maps['day'] + ' 00:00:00'
        e_str = maps['day'] + ' 23:59:59'
        sql += " and register_time >= '%s' and register_time <= '%s'" % (s_str, e_str)
        sql2 += " and register_time >= '%s' and register_time <= '%s'" % (s_str, e_str)
    sql += " order by bid desc limit %d, %d" % (c_num, PAGE_NUM)
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    cont = mysql.getOne(sql2, None)
    mysql.dispose()
    pages = int(math.ceil(cont['con'] / float(PAGE_NUM))) if cont else 0
    route_path = 'get_data'
    html_str = page_code.page_code_html_post(int(p), route_path, pages) if pages > 0 else ''
    data = {}
    data['status'] = 2
    data['page'] = html_str
    if res:
        for d in res:
            d['register_time'] = str(d['register_time']) if d['register_time'] else ''
            d['login_time'] = str(d['login_time']) if d['login_time'] else ''
            d['status'] = '正常' if d['status'] == 1 else '禁用'
            d['money'] = str(d['money'])
        data['res'] = res
        data['p'] = p
        data['status'] = 1
        data['count'] = cont['con']
        data['total_money'] = str(cont['total_money'])
        data['total_num'] = str(cont['total_num'])
    return jsonify(data)


# 更新商户状态
@admin.route('/admin/update_business_post', methods=['post'])
@util.admin_login
def update_business_post():
    uid = request.values.get('uid')
    sid = request.values.get('sid')
    sql = "update user_business SET status = '%s' WHERE bid = '%s'" % (sid, uid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    data = {}
    data['status'] = 2
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 删除商户
@admin.route('/admin/delete_business_post', methods=['post'])
@util.admin_login
def delete_business_post():
    uid = request.values.get('uid')
    sql = "delete FROM user_business WHERE bid = '%s'" % uid
    mysql = Mysql()
    res = mysql.delete(sql, None)
    mysql.dispose()
    data = {}
    data['status'] = 2
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 编辑商户资料
@admin.route('/admin/business_edit.html')
@util.admin_login
def business_edit():
    bid = request.args.get('bid')
    sql = "select * FROM user_business WHERE bid = '%s'" % bid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return render_template('admin/business/business_edit.html', res=res)


# 修改商户资料
@admin.route('/admin/business_edit_post', methods=['post'])
@util.admin_login
def business_edit_post():
    uid = request.values.get('uid')
    # phone = request.values.get('phone')
    info = request.values.get('info')
    # password = request.values.get('password')
    nickname = request.values.get('nickname')
    # if password:
    #     p_str = util.md5(str(password))
    #     sql = "update user_business SET phone = '%s', info = '%s', password = '%s', nickname = '%s' WHERE bid = '%s'" % (phone, info, p_str, nickname, uid)
    # else:
    sql = "update user_business SET  info = '%s', nickname = '%s' WHERE bid = '%s'" % (info, nickname, uid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    data = {}
    data['status'] = 2
    if res > 0:
        data['status'] = 1
    return jsonify(data)


# 系统给商家赠送套餐
@admin.route('/admin/give_business.html')
@util.admin_login
def give_business():
    bid = request.values.get('bid')
    business = gei_business(bid)
    suit = get_suit()
    return render_template('admin/business/give_business.html', business=business, suit=suit)


# 系统给商家赠送处理
@admin.route('/admin/give_business_post', methods=['post'])
@util.admin_login
def give_business_post():
    data = {}
    data['status'] = 0
    try:
        suit = request.values.get('suit')
        bid = request.values.get('bid')
        business = gei_business(bid)
        if business is None:
            data['status'] = 2
            return jsonify(data)
        suit_data = get_one_suit(suit)
        if suit_data is None:
            data['status'] = 3
            return jsonify(data)
        res = give_func(bid, suit_data)
        if res > 0:
            update_business(bid, suit_data['num'])
            data['status'] = 1
    except Exception as e:
        print e
    return jsonify(data)


# 新增商家
@admin.route('/admin/add_business.html')
@util.admin_login
def add_business():
    return render_template('admin/business/add_business.html')


# 新增商家提交
@admin.route('/admin/add_business_post', methods=['post'])
@util.admin_login
def add_business_post():
    data = {}
    data['status'] = 2
    try:
        username = request.values.get('username')
        # password = request.values.get('password')
        # phone = request.values.get('phone')
        info = request.values.get('info')
        user = get_business_username(username)
        if user:
            data['status'] = 3
            return jsonify(data)
        # p_str = util.md5(str(password))
        sql = "insert INTO user_business(nickname,  info, register_time) VALUES ('%s', " \
              "'%s', now())" % (username, info)
        mysql = Mysql()
        res = mysql.insertOne(sql, None)
        mysql.dispose()
        if res > 0:
            data['status'] = 1
    except Exception as e:
        print e
        data['status'] = 500
    return jsonify(data)


# 获取商家
def gei_business(bid):
    sql = "select * FROM user_business WHERE bid = '%s'" % bid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 获取商家套餐
def get_suit():
    sql = "select * FROM business_suit WHERE status = 1"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res


# 获取套餐是否存在
def get_one_suit(suit_id):
    sql = "select * FROM business_suit WHERE suit_id = '%s'" % suit_id
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 系统给商家赠送套餐
def give_func(bid, suit):
    sql = "insert INTO business_pay_log(bid, suit_id, recharge_num, recharge_name, recharge_price, pay_type, add_time)" \
          " VALUES ('%s', '%s', '%s', '%s', '%s', 3, now())" % (bid, suit['suit_id'], suit['num'], suit['name'], suit['price'])
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 更新商家洗车次数
def update_business(bid, num):
    sql = "update user_business SET wash_num = wash_num + '%s' WHERE bid = '%s'" % (num, bid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()


# 查询账号是否被注册
def get_business_username(username):
    sql = "select * FROM user_business WHERE nickname = '%s'" % username
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 商家套餐列表
@admin.route('/admin/business/suit.html', methods=['POST', 'GET'])
@util.admin_login
def admin_business_suit():
    mysql = Mysql()
    sql = "select * from business_suit order by weight ASC, suit_id desc"
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return render_template('admin/business/business_suit.html', res=res)


# 新增套餐
@admin.route('/admin/suit/newly.html', methods=['POST', 'GET'])
@util.admin_login
def admin_suit_newly():
    if request.method == "GET":
        return render_template('admin/business/suit_newly.html')
    else:
        try:
            modelName = request.values.get('suitName')
            price = request.values.get('price')
            num = request.values.get('num')
            ones = request.values.get('ones', 0)
            weight = request.values.get('weight', 1)
            mysql = Mysql()
            sql = "insert into business_suit(name,price,num,ones,weight,add_time)VALUES ('%s','%s','%s','%s','%s',now())" % (
                modelName, price, num, ones, weight)
            result = mysql.update(sql, None)
            code = util.CODE_EMPTY
            mysql.dispose()
            if result > 0:
                code = util.CODE_SUCCESS
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code
        }
        return util.to_json(data)


@admin.route('/admin/suit/stop', methods=['POST'])
@util.admin_login
def admin_suit_stop():
    suitId = request.values.get('suitId')
    mysql = Mysql()
    sql = "update business_suit set status=0 where suit_id='%s'" % suitId
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/suit/start', methods=['POST'])
@util.admin_login
def admin_suit_start():
    suitId = request.values.get('suitId')
    mysql = Mysql()
    sql = "update business_suit set status=1 where suit_id='%s'" % suitId
    res = mysql.update(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


@admin.route('/admin/suit/delete', methods=['POST'])
@util.admin_login
def admin_suit_delete():
    suitId = request.values.get('suitId')
    mysql = Mysql()
    sql = "delete from  business_suit where suit_id='%s'" % suitId
    res = mysql.delete(sql, None)
    mysql.dispose()
    if res > 0:
        data = {
            'status': 1
        }
    else:
        data = {
            'status': 0
        }
    return util.to_json(data)


# 套餐编辑
@admin.route('/admin/suit/edit.html', methods=['POST', 'GET'])
@util.admin_login
def admin_suit_edit():
    if request.method == 'GET':
        suit_id = request.args.get('suit_id')
        mysql = Mysql()
        sql = "select * from business_suit where suit_id='%s'" % suit_id
        result = mysql.getOne(sql, None)
        mysql.dispose()
        return render_template("admin/business/suit_edit.html", res=result)
    else:
        try:
            modelName = request.values.get('name')
            price = request.values.get('price')
            modelId = request.values.get('suit_id')
            num = request.values.get('num')
            ones = request.values.get('ones')
            weight = request.values.get('weight', 1)
            mysql = Mysql()
            sql = "update business_suit set name='%s',price='%s',num='%s', ones='%s', weight = '%s' where suit_id='%s'" % (
                modelName, price, num, ones, weight, modelId)
            result = mysql.update(sql, None)
            code = util.CODE_EMPTY
            mysql.dispose()
            if result > 0:
                code = util.CODE_SUCCESS
        except Exception as e:
            print e
            code = util.CODE_ERROR
        data = {
            'code': code
        }
        return util.to_json(data)


# 购买记录
@admin.route('/admin/pay/log.html', methods=['POST', 'GET'])
@util.admin_login
def admin_pay_log():
    date1 = request.values.get('date1')
    date2 = request.values.get('date2')
    bid = request.values.get('bid')
    page = request.args.get('page', default=1)
    page = int(page)
    num = (page - 1) * util.PAGE_NUM
    mysql = Mysql()
    sql = "select a.*,b.nickname,c.wxNickName,d.name ,d.num as num1  from business_pay_log " \
          "as a left join user_business as b on" \
          " a.bid=b.bid left join car_users as c on c.uid=a.uid left join business_suit as d " \
          "on a.suit_id=d.suit_id where 1=1 "
    sql2 = "select count(*),sum(pay_money) as total_money,sum(d.num) as total_num from business_pay_log as a " \
           " left join business_suit as d on a.suit_id=d.suit_id   where 1=1"
    if bid:
        sql += " and a.bid='%s'" % bid
        sql2 += " and bid='%s'" % bid
    if date1:
        sql += " and a.add_time>='%s'" % date1
        sql2 += " and add_time>='%s'" % date1
    if date2:
        etime_str = date2 + ' 23:59:59'
        sql += ' and a.add_time<="%s"' % etime_str
        sql2 += ' and add_time<="%s"' % etime_str
    sql += " order by a.add_time desc limit %d,%d" % (num, util.PAGE_NUM)
    res = mysql.getAll(sql, None)
    count1 = mysql.getOne(sql2, None)
    count = int(count1['count(*)'])
    if count % util.PAGE_NUM > 0:
        max_page = count / util.PAGE_NUM + 1
    else:
        max_page = count / util.PAGE_NUM
    mysql.dispose()
    data = {
        'res': res,
        'max_page': max_page,
        'page': page,
        'count': count,
        'total_money': count1['total_money'],
        'total_num':count1['total_num']
    }
    return render_template('admin/business/pay_log.html', res=data, business=get_all_business())


# 充值记录
@admin.route('/admin/business/recharge.html', methods=['POST', 'GET'])
@util.admin_login
def admin_business_recharge():
    date1 = request.values.get('date1')
    date2 = request.values.get('date2')
    bid = request.values.get('bid')
    page = request.args.get('page', default=1)
    page = int(page)
    num = (page - 1) * util.PAGE_NUM
    mysql = Mysql()
    sql = "select a.*,b.nickname,c.wxNickName from business_recharge as a left join user_business as b on" \
          " a.bid=b.bid left join car_users as c on c.uid=a.uid  where 1=1  "
    sql2 = "select count(*),sum(pay_money) as total_money  from business_recharge where 1=1 "
    if bid:
        sql += " and a.bid='%s'" % bid
        sql2 += " and bid='%s'" % bid
    if date1:
        sql += " and a.add_time>='%s'" % date1
        sql2 += " and add_time>='%s'" % date1
    if date2:
        etime_str = date2 + ' 23:59:59'
        sql += 'and a.add_time<="%s"' % etime_str
        sql2 += 'and add_time<="%s"' % etime_str
    sql += " order by a.add_time desc limit %d,%d" % (num, util.PAGE_NUM)
    res = mysql.getAll(sql, None)
    count = mysql.getOne(sql2, None)
    count1 = int(count['count(*)'])
    if count1 % util.PAGE_NUM > 0:
        max_page = count1 / util.PAGE_NUM + 1
    else:
        max_page = count1 / util.PAGE_NUM
    mysql.dispose()
    data = {
        'res': res,
        'max_page': max_page,
        'page': page,
        'count': count1,
        'total_money': count['total_money']
    }
    return render_template('admin/business/business_recharge.html', res=data, business=get_all_business())


# 获取所有商家
def get_all_business():
    sql = "select * FROM user_business"
    mysql = Mysql()
    res = mysql.getAll(sql, None)
    mysql.dispose()
    return res
